package org.com.lcuiot.handler;

import org.com.lcuiot.database.dto.Result;
import org.com.lcuiot.security.GetTokenInfo;
import org.com.lcuiot.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.server.RouterFunctions.route;

/**
 * 区域处理器
 *
 * @author gaoge
 * @since 2022/11/21 16:36
 */
@RestController
public class AreaHandler extends AbstractHandler {
    private final AreaService areaService;

    @Autowired
    public AreaHandler(AreaService areaService) {
        this.areaService = areaService;
    }


    @Bean
    public RouterFunction<ServerResponse> areaRouter() {
        return route()
                .GET("/all_area", this::selectByOrganizationId)
                .build();
    }

    /**
     * 查询登陆机构下所有区域
     *
     * @param request 请求信息
     * @return Mono<ServerResponse>
     * @author gaoge
     */
    public Mono<ServerResponse> selectByOrganizationId(ServerRequest request) {
        return GetTokenInfo.getAuthentication().flatMap(auth -> {
                    Result<Object> result = areaService.selectByOrganizationId(auth.getOrganizationId());
                    return resolveResult(result);
                }
        );
    }
}
